package com.srp.backend.service;

import com.srp.backend.dto.LoginRequest;
import com.srp.backend.dto.LoginResponse;
import com.srp.backend.dto.RegisterRequest;
import com.srp.backend.entity.User;
import com.srp.backend.mapper.UserMapper;
import com.srp.backend.common.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    
    @Autowired
    JwtUtil jwtUtil;
    
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public void insertUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void deleteUser(Integer id) {
        userMapper.delete(id);
    }

    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> getUserfuzzily(String username, String name) {
        return userMapper.selectFuzzily(username, name);
    }

    public List<User> getUserByPage(Integer pagenum, Integer pagesize, String username,String name) {
        Integer skipnum=(pagenum-1)*pagesize;
        return userMapper.selectByPage(skipnum,pagesize,username,name);
    }

    public Integer getUserCount(String username, String name) {
        return userMapper.selectCountByPage(username, name);
    }
    
    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        
        // 先根据用户名查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码（使用BCrypt验证加密密码）
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != null && user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(username, user.getId());
        
        // 构建登录响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUsername(user.getUsername());
        response.setName(user.getName());
        response.setEmail(user.getEmail());
        response.setPhone(user.getPhone());
        response.setAvatar(user.getAvatar());
        
        return response;
    }
    
    /**
     * 根据用户名查询用户
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    /**
     * 验证用户密码
     */
    public boolean validatePassword(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return false;
        }
        return passwordEncoder.matches(password, user.getPassword());
    }

    /**
     * 用户注册
     */
    public void register(RegisterRequest request) {
        //  检查用户名是否已存在
        User existingUser = userMapper.findByUsername(request.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 2. 创建用户
        User newUser = User.builder()
                .username(request.getUsername())
                .password(passwordEncoder.encode(request.getPassword()))
                .name(request.getName())
                .phone(request.getPhone())
                .email(request.getEmail())
                .status(1) // 启用
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        // 3. 插入数据库
        int result = userMapper.insert(newUser);
        if (result != 1) {
            throw new RuntimeException("注册失败");
        }
    }
}
